<template>
  <div>
    <a-modal
      :visible="visible"
      :width="560"
      :confirmLoading="loading"
      :maskClosable="false"
      @cancel="cancel"
      @ok="confirm"
    >
      <div slot="title">{{ form.id ? "编辑角色" : "新增角色" }}</div>
      <div>
        <a-form-model ref="form" :model="form" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }">
          <a-form-model-item prop="name" label="名称">
            <a-input v-model="form.name" />
          </a-form-model-item>
          <a-form-model-item prop="remark" label="备注">
            <a-input v-model="form.remark" allowClear />
          </a-form-model-item>
          <a-form-model-item prop="permission_set" label="权限">
            <permission-checkbox v-model="form.permission_set" />
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { roleCreate, roleUpdate } from "@/apis/system";

export default {
  components: {
    PermissionCheckbox: () => import("@/components/PermissionCheckbox"),
  },
  props: ["visible", "form", "roleName"],
  model: { prop: "visible", event: "cancel" },
  data() {
    return {
      rules: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "change" },
          { max: 64, message: "超出最大长度 (64)", trigger: "change" },
        ],
        remark: [{ max: 256, message: "超出最大长度 (256)", trigger: "change" }],
      },
      loading: false,
    };
  },
  methods: {
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;

          let func = this.form.id ? roleUpdate : roleCreate;
          func({ ...this.form })
            .then((data) => {
              this.$message.success(this.form.id ? "修改成功" : "新增成功");
              this.$emit(this.form.id ? "update" : "create", data);
              this.cancel();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    cancel() {
      this.$emit("cancel", false);
      this.$refs.form.resetFields();
    },
  },
};
</script>

<style scoped></style>
